package app.auto.runner.base.utility;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Stack;

import app.auto.AndroidInstance;
import app.auto.runner.base.BroadcastBuilder;
import app.auto.runner.base.intf.FunCallback;
import app.auto.runner.base.intf.MapBuilder;
//step 1 init : Activity onCreate
//step 2 if(BackStack.map(context)!=null){ return BackStack.map(context).backPressed();}
//       : onKeyDown()
//       / ‘extends ActivityBase’
//step 3 use where to listen : BackStack.map(context).onClickBack(new FuncCallBack(){
//         ...
//       })

public class BackStack extends AndroidInstance {


    public BackStack setBACK_STACK(String BACK_STACK) {
        this.BACK_STACK = BACK_STACK;
        return this;
    }

    public String BACK_STACK = "backstack";
    public static final String BACK_STACK_JOB_KEY_CALLBACK = "backstack_job_key_callback";
    public static final String BACK_STACK_ACTION = "backstack_stackaction";

    public Stack stack = new Stack();

    public static Map map = new HashMap();

    public static BackStack map(Activity activityBase) {
        return mapPrivate(activityBase);
    }

    private static BackStack mapPrivate(Activity activityBase) {
        if (!map.containsKey(activityBase)) {
            map.put(activityBase, BackStack.get(BackStack.class, activityBase));
//            BackStack.init(activityBase);
        }
        return (BackStack) map.get(activityBase);
    }

    public Stack getStack() {
        return stack;
    }

    public void registerEvent(Context context, String popView1) {
        BroadcastBuilder.build().sendAction(BACK_STACK, "", context, MapBuilder.build().add(BackStack.BACK_STACK_JOB_KEY_CALLBACK, popView1), BroadcastBuilder.Starttype.broadcast);
    }

    public static void init(Context context) {
        BackStack.map((Activity) context).registerKeyInActivity(true);
    }

    public void removeAllBroadcastKeys() {
        for (Object k : keys) {
            BroadcastBuilder.remove(k.toString(), getContext());
        }
        keys.clear();
    }


    public static List keys = new ArrayList();
    Random random = new Random(7);

    public BackStack onClickRun(final FunCallback popfuncback) {
        onClickRunPrivate(popfuncback);
        return this;
    }

    private void onClickRunPrivate(final FunCallback popfuncback) {
        BackStack.init(getContext());
        String k = random.nextInt() + "";
        keys.add(k);
        BroadcastBuilder.build().receive(k, "", getContext(), new FunCallback() {
            @Override
            public void onCallback(Object result, Object object) {
                super.onCallback(result, object);
                popfuncback.onCallback(result, object);
            }
        });
        registerEvent(getContext(), k);
    }

    public boolean enabled = false;

    public void registerKeyInActivity(boolean addOrRemove) {
        registerKeyInActivityPrivate(addOrRemove);

    }

    private void registerKeyInActivityPrivate(boolean addOrRemove) {
        if (addOrRemove) {
            FrameLayout fl = new FrameLayout(getContext());
            ((Activity) getContext()).addContentView(fl, new ViewGroup.MarginLayoutParams(-1, -1));
            fl.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
                @Override
                public void onViewAttachedToWindow(View v) {

                }

                @Override
                public void onViewDetachedFromWindow(View v) {
//                    ToastUtil.live((Activity) getContext()).toast("detach");
                    registerKeyInActivity(false);
                    map.remove(getContext());
                    release();
                }
            });
            enabled = true;
            BroadcastBuilder.build().receive(BACK_STACK, "", getContext(), new FunCallback() {
                @Override
                public void onCallback(Object result, Object object) {
                    super.onCallback(result, object);
                    Map m = ((Map) ((Intent) object).getSerializableExtra("params"));
                    String jobkey = (String) m.get(BACK_STACK_JOB_KEY_CALLBACK);
                    String action = (String) m.get(BACK_STACK_ACTION);
                    if (!TextUtils.isEmpty(jobkey)) {
                        stack.push(jobkey);
                    } else if (!TextUtils.isEmpty(action)) {
                        if (action.equals("remove")) {
                            stack.pop();
                        }
                    }


                }
            });
        } else {
            if (enabled) {
                BroadcastBuilder.remove(BACK_STACK, getContext());
                removeAllBroadcastKeys();
            }
        }
    }

    public boolean backPressed() {
        if (!getStack().isEmpty()) {

            String key_poped = (String) getStack().peek();
            BroadcastBuilder.build().sendAction(key_poped, "", getContext(), null, BroadcastBuilder.Starttype.broadcast);

            return true;
        }
        return false;
    }

    public void release() {
        getStack().clear();
        map.clear();
    }

    @Override
    public AndroidInstance use(Object mp, Object... p) {
        return null;
    }
}
